#include <iostream>
#include <fstream>
#include <vector>
#include <hpdf.h>


void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void *user_data) {
    std::cerr << "Error: " << error_no << ", Detail: " << detail_no << std::endl;
    exit(1);
}

// 读取 UTF-8 编码的汉字数据
std::vector<std::string> load_chinese_characters(const std::string &filename) {
    std::vector<std::string> characters;
    std::ifstream file(filename);
    std::string line;
    
    while (std::getline(file, line)) {
        for (size_t i = 0; i < line.size(); i += 3) { // UTF-8 编码的汉字占 3 字节
            characters.push_back(line.substr(i, 3));
        }
    }
    return characters;
}

// 生成 PDF
void generate_pdf(const std::vector<std::string> &characters, const std::string &output_file) {
    HPDF_Doc pdf = HPDF_New(error_handler, nullptr);
    if (!pdf) {
        std::cerr << "无法创建 PDF 文档！" << std::endl;
        return;
    }

    HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL);

    // 添加 SimSun 字体
    HPDF_UseCNSEncodings(pdf);
    HPDF_UseCNSFonts(pdf);
    HPDF_Font font = HPDF_GetFont(pdf, "SimSun", "GBK-EUC-H");

    const int chars_per_page = 300;
    const int chars_per_line = 15;
    const int line_height = 20;
    const int margin = 50;

    size_t total_chars = characters.size();
    size_t pages = (total_chars + chars_per_page - 1) / chars_per_page;

    for (size_t p = 0; p < pages; ++p) {
        HPDF_Page page = HPDF_AddPage(pdf);
        HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);
        HPDF_Page_SetFontAndSize(page, font, 12);

        float page_height = HPDF_Page_GetHeight(page);
        float page_width = HPDF_Page_GetWidth(page);

        for (int i = 0; i < chars_per_page; ++i) {
            size_t index = p * chars_per_page + i;
            if (index >= total_chars) break;

            float x = margin + (i % chars_per_line) * 20;
            float y = page_height - margin - (i / chars_per_line) * line_height;

            HPDF_Page_BeginText(page);
            HPDF_Page_TextOut(page, x, y, characters[index].c_str());
            HPDF_Page_EndText(page);
        }
    }

    // 保存 PDF
    HPDF_SaveToFile(pdf, output_file.c_str());
    HPDF_Free(pdf);
}

int main() {
    std::string input_file = "chinese_chars.txt"; // 存放所有汉字的文件
    std::string output_pdf = "output.pdf";

    std::vector<std::string> characters = load_chinese_characters(input_file);
    if (characters.empty()) {
        std::cerr << "无法加载汉字数据！" << std::endl;
        return 1;
    }

    generate_pdf(characters, output_pdf);
    std::cout << "PDF 生成成功: " << output_pdf << std::endl;
    return 0;
}
